import os
import subprocess

VIDEO_ROOT = 'vdeo'
AUDIO_ROOT = 'audio'
VIDEO_EXTS = ['.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv']

def is_video_file(filename):
    return any(filename.lower().endswith(ext) for ext in VIDEO_EXTS)

def convert_video_to_mp3(video_path, audio_path):
    os.makedirs(os.path.dirname(audio_path), exist_ok=True)
    cmd = [
        'ffmpeg', '-y', '-i', video_path, '-vn', '-acodec', 'libmp3lame', '-ar', '44100', '-ac', '2', '-ab', '192k', '-f', 'mp3', audio_path
    ]
    subprocess.run(cmd, check=True)

def main():
    for root, dirs, files in os.walk(VIDEO_ROOT):
        for file in files:
            if is_video_file(file):
                rel_dir = os.path.relpath(root, VIDEO_ROOT)
                audio_dir = os.path.join(AUDIO_ROOT, rel_dir)
                video_path = os.path.join(root, file)
                audio_filename = os.path.splitext(file)[0] + '.mp3'
                audio_path = os.path.join(audio_dir, audio_filename)
                if os.path.exists(audio_path):
                    print(f"[跳过] 已存在: {audio_path}")
                    continue
                print(f"[转换] {video_path} -> {audio_path}")
                try:
                    convert_video_to_mp3(video_path, audio_path)
                except Exception as e:
                    print(f"[错误] 转换失败: {video_path}，原因: {e}")

if __name__ == '__main__':
    main() 